import { PickInputRJSFFormat } from '@app-base/common/components/command-form/constants';
import { RJSFSchema } from '@rjsf/utils';
import { Vector3Tuple } from 'three-legacy';
import {
  getNormalOrId,
  getNormalsOrIds,
  Picktip,
  SetPick,
} from '../cmd-common/tools';

export type RelyOn = {
  name: string;
  entityId: string;
  point: Vector3Tuple;
};
export const args = {
  target: [],
  relyOn: null,
  relyOn1: null,
  relyOn2: null,
};
const shortest = {
  relyOn1: '请选择第一个点',
  relyOn2: '请选择第二个点',
};
const vertical = {
  relyOn1: '请选择面点',
  relyOn2: '请选择边点',
};
export const tip = {
  shortest,
  vertical,
};
export const setSchema: RJSFSchema = {
  type: 'object',
  properties: {
    target: {
      type: 'array',
      items: {
        type: 'string',
        enum: [],
      },
      format: PickInputRJSFFormat.MultiPickFace,
      uniqueItems: true,
    },
    relyOn: SetPick('PickPlane'),
  },
};
export const uiSchema = {
  target: Picktip(true, '多个面'),
  relyOn: Picktip(false, '一个平面'),
};

export type ModeType = 'shortest' | 'vertical' | 'planar';

export type InitType = {
  mode: ModeType;
  target: string[];
  relyOn?: any;
  relyOn1: RelyOn;
  relyOn2: RelyOn;
};

export const OptionType = [
  { value: 'shortest', label: '最短距离切分' },
  { value: 'vertical', label: '垂向切分' },
  { value: 'planar', label: '平面切分' },
];

export type Props = {
  label: string;
  isActive: boolean;
  cmdRef;
  onFocus: () => void;
  options: string[];
  param: InitType;
  relyKey?: 'relyOn1' | 'relyOn2';
  canFocusOther?: boolean;
  canBeAutoFocused?: boolean;
  focusID?: number;
  onRemove?: () => void;
};

export const format = (param: InitType, picked: any) => {
  const ret = {
    mode: param.mode,
    target: null,
    relyOn: null,
  };
  if (param.mode === 'shortest') {
    const id = getNormalOrId(picked, 'id').id;
    ret.target = [id];
    // 处理顶点的情况
    const entityId1 = param.relyOn1?.entityId;
    const entityId2 = param.relyOn2?.entityId;
    ret.relyOn = [
      entityId1.split(':')?.[1].includes('v')
        ? param.relyOn1.entityId
        : [param.relyOn1.entityId, ...param.relyOn1.point],
      entityId2.split(':')?.[1].includes('v')
        ? param.relyOn2.entityId
        : [param.relyOn2.entityId, ...param.relyOn2.point],
    ];
  } else if (param.mode === 'vertical') {
    ret.target = [[param.relyOn1.entityId, ...param.relyOn1.point]];
    ret.relyOn = [[param.relyOn2.entityId, ...param.relyOn2.point]];
  } else {
    const ids = getNormalsOrIds(param.target, 'id').map((item) => item.id);
    const id = getNormalOrId(param.relyOn, 'id').id;
    ret.target = ids;
    ret.relyOn = [id];
  }
  return ret;
};
